import React, { useState, useRef, useEffect } from 'react';
import { Avatar, Input, Modal, Select,Tag, message, AutoComplete } from 'antd';
import debounce  from 'lodash.debounce';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { TableListItem } from '../../Program/data.d';
import PreviewModel from '../../Program/components/PreviewModel';
import TemplateModel from '../components/templateModel';
import DataSourceModel from '../components/dataSourceModel';
import { PlanTimeListParams } from '../data.d';
import {programList} from '../../Program/service';
import styles from '../index.less';
import styles1 from '../../Program/index.less';

interface CreateFormProps {
  modalVisible: boolean;
  playMode: boolean;
  values:PlanTimeListParams;
  onSubmit: (values:PlanTimeListParams) => void;
  onCancel: () => void;
}

const { Search } = Input;
const { Option } = Select;

const ProgramModel: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, values, playMode, onSubmit, onCancel } = props;
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState<TableListItem[]>([]);
  const [formValues, setFormValues] = useState({});
  const [previewModalVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [templateModalVisible, handleTemplateModalVisible] = useState<boolean>(false);
  const [dataSourceModalVisible, handleDataSourceModalVisible] = useState<boolean>(false);
  
  const handleSubmit = () => {
    const list = [];
    for(let i in selectedRows){
      let obj = new Object();
      let row = selectedRows[i];
      obj["id"] = row.id;
      obj["key"] = row.key;
      obj["seq"] = i;
      obj["name"] = row.name;
      obj["totalTime"] = row.totalTime
      obj["previewImgUrl"] = row.previewImgUrl;
      obj["resolution"] = row.resolution;
      list.push(obj);
    }
    if(list.length == 0){
      message.warn('请至少选择一个节目');
      return;
    }
    values.programList = list;
    onSubmit(values);
  }
  const modalFooter = { okText: '保存', onOk: handleSubmit, onCancel };

  useEffect(() => {
    if(props.modalVisible){
      let array = [];
      if(values){
        console.log(values)
        // if(playMode){ //持续播放
          for(let i in values.programList){
            array.push(parseInt(values.programList[i].id));
          }
          setSelectedRowKeys(array);
          setSelectedRows(values.programList);
        // }
        // else{ //按时段播放
        //   for(let i in values.programList){
        //     array.push(parseInt(values.programList[i].id));
        //   }
        //   setSelectedRowKeys(array);
        //   setSelectedRows(values.programList);
        // }
      }
    }
  },[props.modalVisible]);
 
  const handleClose = () => {
    handlePreviewModalVisible(false);
    var id = window.setTimeout(function () {}, 0);
    while (id--) {
      window.clearTimeout(id);
    } //停止计数器
  };

  const showPreviewModel = (record:TableListItem) =>{
    setFormValues(record);
    handlePreviewModalVisible(true);
  }

  const showTemplateModel = (id:string) =>{
    handleTemplateModalVisible(true);
  }

  const templateModelCancel = () =>{
    handleTemplateModalVisible(false);
  }

  const showDataSourceModel = (id:string) =>{
    handleDataSourceModalVisible(true);
  }

  const dataSourceModelCancel = () =>{
    handleDataSourceModalVisible(false);
  }

 const columns: ProColumns<TableListItem>[] = [
    {
      title: '缩略图',
      dataIndex: 'previewImgUrl',
      width:80,
      valueType: 'text',
      hideInSearch: true, 
      className: styles1.thumb,
      render: (_, record) => <Avatar src={record.previewImgUrl} shape="square" size="large"/>,
    },
    {
      title: '节目名称',
      dataIndex: 'name',
      ellipsis: true,
      width:200,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入节目名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
      render: (_, record) => 
        <a 
          style={{display:'block',overflow:'hidden',width:200,textOverflow:'ellipsis',whiteSpace:'nowrap'}}
          title={record.name}
          onClick={() => {showPreviewModel(record)}}
          >{record.name}</a>,
    },
    {
      title: '分辨率',
      dataIndex: 'resolution',
      width:100,
      formItemProps:{
        rules:[
          {
            validator: (rule, value, callback) => {
              if(value){
                const n=(value.split('x')).length-1;
                if(n == 1){
                  callback();
                }else{
                  callback("分辨率只能包含一个x，介于长和宽中间");
                }
              }else{
                callback();
              }
            },
          }
        ],
      },  
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <AutoComplete
              style={{ width: 150 }}
              options={[{ label:"全部分辨率",value:''}, { value: '1920x1080' }, { value: '1080x1920' }]}
              onSelect={(value) => {form.submit()}}
            >
              <Input.Search  
                allowClear 
                placeholder="分辨率" 
                onSearch={(value) => {form.submit()}}
              />
            </AutoComplete>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '节目时长',
      dataIndex: 'totalTime',
      width:80,
      valueType: 'text',
      hideInSearch: true,
      render: (_, record) => <>{record.totalTime}秒</>,
    },
    {
      title: '节目大小',
      dataIndex: 'totalSize',
      width:80,
      valueType: 'text',
      hideInSearch: true,
    },
    // {
    //   title: '设备类型',
    //   dataIndex: 'deviceType',
    //   width:80,
    //   valueType: 'text',
    //   hideInSearch: true,
    // },
    // {
    //   title: '关联模板',
    //   dataIndex: 'template',
    //   width:80,
    //   valueType: 'text',
    //   hideInSearch: true, 
    //   render: (_, record) => <a onClick={() => {showTemplateModel(record.id)}}>模板mock</a>,
    // },
    // {
    //   title: '关联数据源',
    //   dataIndex: 'dataSource',
    //   hideInForm: true,
    //   valueType: 'text',
    //   hideInSearch: true, 
    //   render: (_, record) => <ul style={{margin:0,padding:0,fontSize:12}}>
    //       <li>
    //         <a onClick={() => {showDataSourceModel(record.id)}}>商品名称1-itemcode1</a>
    //       </li>
    //       <li>
    //         <a onClick={() => {showDataSourceModel(record.id)}}>商品名称2-itemcode2</a>
    //       </li>
    //     </ul>,
    // },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      hideInSearch: true,
      width:150,
      render: tags => (
        <>
          {tags?.map((tag, index) => {
            return (
              <Tag color="blue" key={index} title={tag.name} style={{marginBottom:5,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:130}}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
  ];

  return (
    <Modal
      className={styles.ProgramModel}
      width={900}
      destroyOnClose
      centered
      title="添加节目"
      visible={modalVisible}
      values={values}
      {...modalFooter}
    >
      <ProTable<TableListItem>
        headerTitle="建议选择与相同分辨率的节目以获取最优显示效果"
        size="small"
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 70,
          span:10,
          collapsed: false,
          collapseRender:()=>false //隐藏收起按钮
        }}
        pagination={{ showQuickJumper: true, defaultPageSize: 10 }} //默认每页显示10条
        request={(params, sorter, filter) => programList(params, sorter, filter)}
        columns={columns}
        onLoad={()=>{
          setSelectedRowKeys(selectedRowKeys);
          setSelectedRows(selectedRows);
        }}
        rowSelection={{
          selectedRowKeys:selectedRowKeys,
          onSelect:(record, selected)=>{
            if(selected){//选中
              setSelectedRowKeys([...selectedRowKeys,record.key]);
              setSelectedRows([...selectedRows,record]);
            }else{//取消选中
              const newKeys = selectedRowKeys.concat();
              const index = newKeys.indexOf(record.key);
              newKeys.splice(index, 1);
              setSelectedRowKeys(newKeys);
              
              const newRows = selectedRows.concat();
              for(let i=0;i<selectedRows.length;i++){
                if(i == index){
                  newRows.splice(index, 1);
                }
              }
              setSelectedRows(newRows);
            }
          },
          onSelectAll:(selected, selectedRows1, changeRows)=>{
            if(selected){//全选
              const keys = [];
              for(let i=0;i<changeRows.length;i++){
                const record = changeRows[i];
                keys.push(record.key);
              }
              setSelectedRowKeys([...selectedRowKeys,...keys]);
              setSelectedRows([...selectedRows,...changeRows]);
            }else{//取消全选
              const newSelectedRowKeys = selectedRowKeys.concat();
              const newSelectedRows = selectedRows.concat();
              for(let i=0;i<changeRows.length;i++){
                const record = changeRows[i];
                for(let j=0;j<newSelectedRowKeys.length;j++){
                  if(record.key == newSelectedRowKeys[j]){
                    newSelectedRowKeys.splice(j, 1);
                    newSelectedRows.splice(j, 1);
                  }
                }
              }
              setSelectedRowKeys(newSelectedRowKeys);
              setSelectedRows(newSelectedRows);
            }
          }
        }}
        tableAlertOptionRender={() => {
          return (<a onClick={() => {
            setSelectedRowKeys([]);
            setSelectedRows([]);
            actionRef.current?.clearSelected?.();
          }}>清空</a>)
        }}
        scroll={{y:240}}
      />
      <PreviewModel modalVisible={previewModalVisible} values={formValues} onCancel={handleClose}>
        <ProTable<TableListItem, TableListItem> />
      </PreviewModel>
      <TemplateModel modalVisible={templateModalVisible} values={formValues} onCancel={templateModelCancel}>
      </TemplateModel>
      <DataSourceModel modalVisible={dataSourceModalVisible} values={formValues} onCancel={dataSourceModelCancel}>
      </DataSourceModel>
    </Modal>
  );
};

export default ProgramModel;
